import {
  commType,
  dislikeCommentAPI,
  getCommentsByIdAPI,
  likeCommentAPI,
  ParamsType,
  submitCommentAPI,
} from '@/api/common';
import { AppDispatch } from '..';
import { CommentType } from '../reducer/common';

//    2. 封装Action函数
export const getCommentsByIdAction = (params: ParamsType) => {
  return async (dispatch: AppDispatch) => {
    // 4. 修改loading为true
    dispatch({ type: 'comment/setLoading', payload: true });
    const res = await getCommentsByIdAPI(params);
    dispatch({ type: 'comment/saveList', payload: res.data.results });
    // 5. 加载成功后，关闭加载状态
    dispatch({ type: 'comment/setLoading', payload: false });
  };
};

// 3. 清除的action
export const clearCommentsAction = () => {
  return {
    type: 'comment/saveList',
    payload: [],
  };
};

// 4. 定义action函数
export const saveOriginCommentAction = (commentData: CommentType) => {
  return {
    type: 'comment/saveOrigiComment',
    payload: commentData,
  };
};

// 4. 定义action函数
export const clearOriginCommentAction = () => {
  return {
    type: 'comment/clearOrigiComment',
  };
};

export const submitCommentAction = (data: commType) => {
  return async (dispatch: AppDispatch) => {
    await submitCommentAPI(data);
  };
};

// 2. 获取评论列表的Action
export const getReplyCommentsByIdAction = (com_id: string) => {
  return async (dispatch: AppDispatch) => {
    const res = await getCommentsByIdAPI({ type: 'c', source: com_id });
    dispatch({ type: 'comment/savereplyComment', payload: res.data });
  };
};
export const clearReplyCommentsAction = () => {
  return {
    type: 'comment/saveReplyList',
    // 3. 💥使用初始值清除redux数据
    payload: {
      end_id: '',
      last_id: '',
      results: [],
      total_count: 0,
    },
  };
};

/** 点赞获取取消点赞的action */
export const likeCommentsAction = (id: string, isLiking: boolean) => {
  return async (dispach: AppDispatch) => {
    if (!isLiking) {
      await likeCommentAPI(id);
      dispach({ type: 'comment/updateCommentById', payload: id });
      return;
    }
    await dislikeCommentAPI(id);
    dispach({ type: 'comment/updateCommentById', payload: id });
  };
};

// 4. 定义action函数
export const likeReplyCommentsAction = (id: string, isLiking: boolean) => {
  return async (dispach: AppDispatch) => {
    if (!isLiking) {
      await likeCommentAPI(id);
      dispach({ type: 'comment/updateReplyCommentById', payload: id });
      return;
    }
    await dislikeCommentAPI(id);
    dispach({ type: 'comment/updateReplyCommentById', payload: id });
  };
};

// 3.  定义一个更新原始数据的acton
export const likeOriginCommentsAction = (id: string, isLiking: boolean) => {
  return async (dispatch: AppDispatch) => {
    if (!isLiking) {
      await likeCommentAPI(id);
      dispatch({ type: 'comment/updateOriginComment' });
      return;
    }
    await dislikeCommentAPI(id);
    dispatch({ type: 'comment/updateOriginComment' });
  };
};
